package com.daring.mysql2maxkb;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import okhttp3.*;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AIUtils {

    public static JSONObject generateTitle(String s) throws IOException {

            OkHttpClient client = new OkHttpClient().newBuilder()
                    .connectTimeout(120, TimeUnit.SECONDS) // 连接超时
                    .readTimeout(120, TimeUnit.SECONDS) // 读取超时
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "{\r\n    \"model\": \"chatglm3-6b\",\r\n    \"messages\": [\r\n        {\r\n            \"role\": \"system\",\r\n            \"content\": \"Please create a title in one sentence for the following content, with a minimum word count of 50\"\r\n        },\r\n        {\r\n            \"role\": \"user\",\r\n            \"content\": \""+s+"\"\r\n        }\r\n    ],\r\n    \"stream\": false,\r\n    \"max_tokens\": 100,\r\n    \"temperature\": 0.8,\r\n    \"top_p\": 0.8\r\n}");
            Request request = new Request.Builder()
                    .url("http://219.159.152.7:8501/v1/chat/completions")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                // 一次性读取所有字节
                String resultStr = "";
                try {
                    resultStr = responseBody.string();
                }catch (java.io.InterruptedIOException e){
                    e.printStackTrace();
                }
                JSONObject jsonObject = JSONObject.parseObject(resultStr);
                String title = (String)((JSONObject) ((JSONObject) ((JSONArray) jsonObject.get("choices")).get(0)).get("message")).get("content");
                return new JSONObject(){{
                    put("title", title.replace("\n", ""));
                    put("content", s);
                }};
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new JSONObject(){{
            put("title", "");
            put("content", s);
        }};
    }
    public static HashMap<String, String> generateTitle2(String s) throws UnirestException {
        try {
            Unirest.setTimeouts(0, 0);
            HttpResponse<String> stringHttpResponse = Unirest.post("http://219.159.152.7:8501/v1/chat/completions")
                    .header("Content-Type", "application/json")
                    .body("{\r\n    \"model\": \"chatglm3-6b\",\r\n    \"messages\": [\r\n        {\r\n            \"role\": \"system\",\r\n            \"content\": \"Please create a title in one sentence for the following content, with a minimum word count of 50\"\r\n        },\r\n        {\r\n            \"role\": \"user\",\r\n            \"content\": \"" + s + "\"\r\n        }\r\n    ],\r\n    \"stream\": false,\r\n    \"max_tokens\": 1000000,\r\n    \"temperature\": 0.8,\r\n    \"top_p\": 0.8\r\n}")
                    .asString();
            if (stringHttpResponse != null && stringHttpResponse.getStatus() == 200) {
                String resultStr = stringHttpResponse.getBody();
                if (resultStr != null) {
                    JSONObject jsonObject = JSONObject.parseObject(resultStr);
                    String title = (String)((JSONObject) ((JSONObject) ((JSONArray) jsonObject.get("choices")).get(0)).get("message")).get("content");
                    String replace = title.replace("\n", "").replaceAll("\"", "");
                    return new HashMap<String, String>(){{
                        put("title", replace);
                        put("content", s);
                    }};
                } else {
                    System.err.println("Received empty response body from server.");
                }
            } else {
                System.err.println("HTTP request failed with status: " + (stringHttpResponse != null ? stringHttpResponse.getStatus() : "null"));
            }
        } catch (Exception e) {
            System.err.println("An error occurred during HTTP request: " + e.getMessage());
            e.printStackTrace();
        }
        return new HashMap<String, String>(){{
            put("title", "");
            put("content", s);
        }};




        /*Unirest.setTimeouts(0, 0);

            HttpResponse<String> stringHttpResponse = Unirest.post("http://219.159.152.7:8501/v1/chat/completions")
                    .header("Content-Type", "application/json")
                    .body("{\r\n    \"model\": \"chatglm3-6b\",\r\n    \"messages\": [\r\n        {\r\n            \"role\": \"system\",\r\n            \"content\": \"Please create a title in one sentence for the following content, with a minimum word count of 50\"\r\n        },\r\n        {\r\n            \"role\": \"user\",\r\n            \"content\": \"" + s + "\"\r\n        }\r\n    ],\r\n    \"stream\": false,\r\n    \"max_tokens\": 100,\r\n    \"temperature\": 0.8,\r\n    \"top_p\": 0.8\r\n}")
                    .asString();
            HttpResponse<String> response = stringHttpResponse;
            if (response.getStatus() == 200) {
                String resultStr = response.getBody();
                JSONObject jsonObject = JSONObject.parseObject(resultStr);
                String title = (String)((JSONObject) ((JSONObject) ((JSONArray) jsonObject.get("choices")).get(0)).get("message")).get("content");
                System.out.println(title);
                return new JSONObject(){{
                    put("title", title.replace("\n", ""));
                    put("content", s);
                }};
            }

        return new JSONObject(){{
            put("title", "");
            put("content", s);
        }};*/

    }

    public static void main(String[] args) throws IOException, UnirestException {
        String s = "1月20日，自治区党委书记郭声琨参加了自治区政协十届一次会议经济界委员的讨论。在认真听取委员们的发言后，郭声琨说，要适应新形势新任务新要求，进一步解放思想，把握区情，发现规律，消除瓶颈，破解难题，毫不动摇地支持非公经济的发展，做大做强非公经济，促进广西经济又好又快地发展。郭声琨强调，解放思想是广西加快发展的一大法宝，抓住了广西发展的主要矛盾。广西应该继续坚持把解放思想作为推动经济发展的一个重要途径。从广西的发展历程看，每一次思想的大解放都促进了经济的大发展、投资的大投入。思想解放与改革开放密切相关，思想解放不了，改革开放就没法继续推进。解放思想，就要克服下面几种倾向：第一种是不敢解放，害怕解放思想就会越轨，就会与上级的方针政策有抵触，总是搞一些形而上学、生搬硬套的东西，总是搬出一些旧的框框套套来约束自己；第二种是不想解放，每次思想解放都会推动一些深层次的变革，这就不可避免地触动部门和局部的利益，一些部门囿于自身利益、部门利益而不想改革；第三种是不会解放，原因是工作经验的不足或者知识面的缺乏，比如在金融、企业上市、企业重组和支持非公经济发展等方面，一些同志缺乏这方面的知识，难以作出判断。我们一定要克服以上倾向，进一步解放思想，以思想大解放推动经济社会大发展。郭声琨强调，要准确把握广西区情，发现发展规律，找出影响广西发展的主要矛盾，不断促进经济社会又好又快发展。广西的区情主要表现为人口多、底子薄、发展滞后，属于投资拉动型经济，处于工业化初始阶段。这些年广西有很大发展，但与发达地区相比差距仍然很大，有些差距甚至在扩大，人均水平也不高，无论是综合实力还是产业基础等方面底子都很薄弱，要赶上全国平均发展水平，同步进入小康社会，压力相当大。全区上下一定要增强紧迫感和忧患意识，正确认清形势，准确把握区情，逐步消除发展瓶颈，破解发展难题。特别是要抓住国家批复广西北部湾经济区发展规划的历史机遇，扎实工作，开拓奋进，实现跨越式发展。要大力发展交通事业，加快铁路、公路、民航、海运等交通基础设施建设，形成内外循环畅通、现代立体交通体系，把广西北部湾经济区建设成为中国——东盟开放合作的物流基地、商贸基地、加工制造基地和信息交流中心，成为带动、支撑西部大开发的战略高地和开放度高、辐射力强、经济繁荣、社会和谐、生态良好的重要国际区域经济合作区。要努力解决发展过程中遇到的资金问题，多渠道筹措建设资金，加强银企合作，加快“引金入桂”步伐，抓紧一批条件成熟的企业上市或发行企业债券，扩大直接融资规模，为加快做强做大企业、促进经济发展服务。郭声琨指出，发展非公经济是加快广西发展的有效途径。非公经济具有机制灵活、就业拉动大等优势，与发达地区相比，广西的非公经济比例偏低。要毫不动摇地支持非公经济的发展，落实相关政策，营造创业氛围。认真解决影响非公经济发展的市场准入门槛高、关卡多、融资难等问题，在政策、金融及畅通市场准入等方面加大支持力度，做好服务工作。非公企业要加大管理力度，加大做强做大步代，为推进加快广西发展作出贡献。";
        HashMap<String, String> jsonObject = generateTitle2(s);
        System.out.println("jsonObject = " + jsonObject);
    }

    public static HashMap<String, Object> generateQuests(HashMap<String, String> stringStringHashMap) {
        try {
            Unirest.setTimeouts(0, 0);
            HttpResponse<String> stringHttpResponse = Unirest.post("http://219.159.152.7:8501/v1/chat/completions")
                    .header("Content-Type", "application/json")
                    .body("{\r\n    \"model\": \"chatglm3-6b\",\r\n    \"messages\": [\r\n        {\r\n            \"role\": \"system\",\r\n            \"content\": \"The following is the text content I have provided, which must be answered in Chinese. Please list 10 questions that users are most likely to ask based on the content, and return no less than 10 questions. The format of the return must be strictly used: [{\\\"index\\\": \\\"1\\\", \\\"content\\\": \\\"Is this Question 1?\\\"}, {\\\"index\\\": \\\"2\\\", \\\"content\\\": \\\"Is this Question 2?\\\"}, {\\\"index\\\": \\\"3\\\", \\\"content\\\": \\\"Is this Question 3?\\\"}, {\\\"index\\\": \\\"4\\\", \\\"content\\\": \\\"Is this Question 4?\\\"}, {\\\"index\\\": \\\"5\\\", \\\"content\\\": \\\"Is this Question 5?\\\"}, {\\\"index\\\": \\\"6\\\", \\\"content\\\": \\\"Is this Question 6?\\\"}, {\\\"index\\\": \\\"7\\\", \\\"content\\\": \\\"Is this Question 7?\\\"}, {\\\"index\\\": \\\"8\\\", \\\"content\\\": \\\"Is this Question 8?\\\"}, {\\\"index\\\": \\\"9\\\", \\\"content\\\": \\\"Is this Question 9?\\\"}, {\\\"index\\\": \\\"10\\\", \\\"content\\\": \\\"Is this Question 10?\\\"}]\"\r\n        },\r\n        {\r\n            \"role\": \"user\",\r\n            \"content\": \"" + stringStringHashMap.get("content") + "\"\r\n        }\r\n    ],\r\n    \"stream\": false,\r\n    \"max_tokens\": 100000000,\r\n    \"temperature\": 0.8,\r\n    \"top_p\": 0.8\r\n}")
                    .asString();
            if (stringHttpResponse != null && stringHttpResponse.getStatus() == 200) {
                String resultStr = stringHttpResponse.getBody();
                if (resultStr != null) {
                    JSONObject jsonObject = JSONObject.parseObject(resultStr);
                    String title = (String)((JSONObject) ((JSONObject) ((JSONArray) jsonObject.get("choices")).get(0)).get("message")).get("content");
                    String replace = title.replace("\n", "");
                    Pattern pattern = Pattern.compile("\\{\\\"index\\\"\\: \\\".*?\\\"\\, \\\"content\\\"\\: \\\".*?\\\"\\}");
                    Matcher matcher = pattern.matcher(replace);
                    ArrayList<HashMap<String, String>> problem_list = new ArrayList<>();
                    while (matcher.find()) {
                        String group = matcher.group();
                        String contentValue = group.replaceAll("\\{.*?\"content\": \\\"(.*?)\\\".*?}", "$1");
                        //System.out.println("Content value: " + contentValue);
                        problem_list.add(new HashMap<String, String>(){{
                            put("content", contentValue);
                        }});
                    }
                    return new HashMap<String, Object>(){{
                        put("title", stringStringHashMap.get("title"));
                        put("content", stringStringHashMap.get("content"));
                        put("problem_list", problem_list);
                    }};
                } else {
                    System.err.println("Received empty response body from server.");
                }
            } else {
                System.err.println("HTTP request failed with status: " + (stringHttpResponse != null ? stringHttpResponse.getStatus() : "null"));
            }
        } catch (Exception e) {
            System.err.println("An error occurred during HTTP request: " + e.getMessage());
            e.printStackTrace();
        }
        return new HashMap<String, Object>(){{
            put("title", stringStringHashMap.get("title"));
            put("content", stringStringHashMap.get("content"));
        }};
    }
}
